import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  message,
  Statistic,
  Row,
  Col,
  Modal,
  Typography,
  Badge,
  Tooltip,
  Tabs,
  Empty,
  Popconfirm,
  Select,
  DatePicker,
  Input,
  List,
  Progress,
  Alert
} from 'antd';
import {
  ReloadOutlined,
  DownloadOutlined,
  HistoryOutlined,
  TrophyOutlined,
  CalendarOutlined,
  DatabaseOutlined,
  DeleteOutlined,
  EyeOutlined,
  FilterOutlined,
  ThunderboltOutlined,
  FireOutlined,
  CloudOutlined,
  BulbOutlined,
  ClearOutlined,
  CalculatorOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined,
  MedicineBoxOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Search } = Input;

/**
 * 选号记录页面组件
 * 整合来自智能选号系统和其他界面的选号数据
 */
const LotteryPickingRecords = ({ isMobile = false, historyData = [] }) => {
  const [loading, setLoading] = useState(false);
  const [pickingRecords, setPickingRecords] = useState([]);
  const [filteredRecords, setFilteredRecords] = useState([]);
  const [activeTab, setActiveTab] = useState('records');
  const [diagnosisVisible, setDiagnosisVisible] = useState(false);
  const [diagnosisResults, setDiagnosisResults] = useState([]);
  const [diagnosisLoading, setDiagnosisLoading] = useState(false);
  const [batchDiagnosisLoading, setBatchDiagnosisLoading] = useState(false);
  const [filters, setFilters] = useState({
    algorithm: 'all',
    dateRange: null,
    searchText: '',
    source: 'all'
  });
  const [statistics, setStatistics] = useState({
    total: 0,
    algorithms: {},
    recentCount: 0
  });

  /**
   * 从数据库加载所有选号记录
   */
  const loadPickingRecords = useCallback(async () => {
    try {
      setLoading(true);
      
      // 从统一的选号记录表加载所有记录
      const { DatabaseService } = await import('./database.js');
      const allRecords = await DatabaseService.getAllPickingRecords();
      
      // 转换为统一格式
      const formattedRecords = allRecords.map(record => ({
        id: record.id,
        numbers: {
          red: record.redBalls,
          blue: record.blueBalls
        },
        algorithm: record.algorithm,
        timestamp: record.timestamp,
        predicted: record.predicted || false,
        note: record.note || '',
        source: record.source,
        sourceName: record.sourceName,
        createTime: record.createTime
      }));
      
      setPickingRecords(formattedRecords);
      setFilteredRecords(formattedRecords);
      
      // 计算统计信息
      calculateStatistics(formattedRecords);
      
      console.log(`成功加载 ${formattedRecords.length} 条选号记录`);
    } catch (error) {
      console.error('加载选号记录失败:', error);
      message.error(`加载选号记录失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  }, []);

  /**
   * 计算统计信息
   */
  const calculateStatistics = (records) => {
    const algorithms = {};
    const now = Date.now();
    const oneDayAgo = now - 24 * 60 * 60 * 1000;
    
    let recentCount = 0;
    
    records.forEach(record => {
      // 统计算法使用情况
      const algorithm = record.algorithm || 'unknown';
      algorithms[algorithm] = (algorithms[algorithm] || 0) + 1;
      
      // 统计最近24小时的记录
      if (record.id > oneDayAgo) {
        recentCount++;
      }
    });
    
    setStatistics({
      total: records.length,
      algorithms,
      recentCount
    });
  };

  /**
   * 应用筛选条件
   */
  const applyFilters = useCallback(() => {
    let filtered = [...pickingRecords];
    
    // 算法筛选
    if (filters.algorithm !== 'all') {
      filtered = filtered.filter(record => record.algorithm === filters.algorithm);
    }
    
    // 日期范围筛选
    if (filters.dateRange && filters.dateRange.length === 2) {
      const [startDate, endDate] = filters.dateRange;
      const startTime = startDate.startOf('day').valueOf();
      const endTime = endDate.endOf('day').valueOf();
      
      filtered = filtered.filter(record => {
        const recordTime = record.id || record.timestamp;
        return recordTime >= startTime && recordTime <= endTime;
      });
    }
    
    // 来源筛选
    if (filters.source !== 'all') {
      filtered = filtered.filter(record => record.source === filters.source);
    }
    
    setFilteredRecords(filtered);
    
    // 重新计算统计信息
    calculateStatistics(filtered);
  }, [pickingRecords, filters]);

  // 组件加载时获取选号记录
  useEffect(() => {
    loadPickingRecords();
  }, [loadPickingRecords]);

  // 筛选条件变化时重新应用筛选
  useEffect(() => {
    applyFilters();
  }, [applyFilters]);

  /**
   * 删除选号记录
   */
  const deleteRecord = async (recordId) => {
    try {
      // 从统一的数据库表删除记录
      const { DatabaseService } = await import('./database.js');
      await DatabaseService.deletePickingRecord(recordId);
      
      // 重新加载数据
      await loadPickingRecords();
      message.success('记录已删除');
    } catch (error) {
      console.error('删除记录失败:', error);
      message.error('删除记录失败');
    }
  };

  /**
    * 清空所有记录
    */
   const clearAllRecords = async () => {
     try {
       // 从统一的数据库表清空所有记录
       const { DatabaseService } = await import('./database.js');
       await DatabaseService.clearAllPickingRecords();
       
       setPickingRecords([]);
       setFilteredRecords([]);
       setStatistics({ total: 0, algorithms: {}, recentCount: 0 });
       
       // 发送全局事件通知其他组件刷新数据
       window.dispatchEvent(new CustomEvent('pickingRecordsCleared'));
       
       message.success('所有选号记录已清空');
     } catch (error) {
       console.error('清空记录失败:', error);
       message.error('清空记录失败');
     }
   };

   /**
    * 清理异常时间数据
    */
   const cleanupAbnormalTimeData = async () => {
     try {
       const { DatabaseService } = await import('./database.js');
       const cleanedCount = await DatabaseService.cleanupAbnormalTimeData();
       message.success(`已清理 ${cleanedCount} 条异常时间数据`);
       // 重新加载数据
       await loadPickingRecords();
     } catch (error) {
       console.error('清理异常时间数据失败:', error);
       message.error('清理异常时间数据失败');
     }
   };

   /**
    * 解析历史开奖号码字符串
    */
   const parseHistoryNumbers = (record) => {
     try {
       // 数据库中的格式：
       // record.number: "03 04 17 19 25 27" (红球，空格分隔)
       // record.refernumber: "14" (蓝球)
       
       if (!record || !record.number || !record.refernumber) {
         console.warn('记录格式不正确:', record);
         return null;
       }
       
       // 解析红球号码
       const redBalls = record.number.split(/\s+/)
         .map(n => parseInt(n.trim()))
         .filter(n => !isNaN(n) && n >= 1 && n <= 33);
         
       // 解析蓝球号码
       const blueBall = parseInt(record.refernumber.trim());
       
       if (redBalls.length === 6 && !isNaN(blueBall) && blueBall >= 1 && blueBall <= 16) {
         return { redBalls, blueBall };
       }
       
       console.warn('解析后的号码格式不正确:', { redBalls, blueBall, record });
       return null;
     } catch (error) {
       console.error('解析历史号码失败:', error, record);
       return null;
     }
   };

   /**
    * 分析号码重复度的算法
    */
   const analyzeDuplication = (currentRedBalls, currentBlueBall, historyData) => {
     const analysis = {
       totalDuplicates: 0,
       redDuplicates: 0,
       blueDuplicates: 0,
       duplicateDetails: [],
       riskLevel: 'low',
       suggestions: []
     };

     // 分析每一期的重复情况
     historyData.forEach((record, index) => {
       if (!record.number || !record.refernumber) return;
       
       // 解析历史开奖号码
       const historyNumbers = parseHistoryNumbers(record);
       if (!historyNumbers) return;

       const { redBalls: historyRed, blueBall: historyBlue } = historyNumbers;
       
       // 计算红球重复
       const redMatches = currentRedBalls.filter(ball => historyRed.includes(ball));
       
       // 计算蓝球重复
       const blueMatch = currentBlueBall === historyBlue;
       
       if (redMatches.length > 0 || blueMatch) {
         analysis.duplicateDetails.push({
           period: record.issueno || `第${index + 1}期`,
           date: record.opendate,
           redMatches: redMatches,
           blueMatch: blueMatch,
           blueNumber: historyBlue, // 添加蓝球号码
           totalMatches: redMatches.length + (blueMatch ? 1 : 0)
         });
       }
       
       analysis.redDuplicates += redMatches.length;
       analysis.blueDuplicates += blueMatch ? 1 : 0;
     });

     analysis.totalDuplicates = analysis.redDuplicates + analysis.blueDuplicates;

     // 确定风险等级
     if (analysis.totalDuplicates >= 4) {
       analysis.riskLevel = 'high';
       analysis.suggestions.push('建议重新选择号码，重复度过高');
     } else if (analysis.totalDuplicates >= 2) {
       analysis.riskLevel = 'medium';
       analysis.suggestions.push('存在一定重复风险，建议调整部分号码');
     } else {
       analysis.riskLevel = 'low';
       analysis.suggestions.push('重复度较低，号码选择合理');
     }

     return analysis;
   };

   /**
    * 诊断单个选号记录
    */
   const diagnoseSingleRecord = async (record) => {
     try {
       const { redBalls, blueBalls } = formatNumbers(record.numbers);
       
       if (redBalls.length !== 6 || blueBalls.length !== 1) {
         throw new Error('号码格式不正确');
       }

       // 获取最近3期的开奖记录
       const { DatabaseService } = await import('./database.js');
       const recentHistory = await DatabaseService.getRecentLotteryHistory(3);
       
       if (recentHistory.length === 0) {
         throw new Error('暂无历史开奖记录，无法进行诊断');
       }

       // 分析重复度
       const analysis = analyzeDuplication(redBalls, blueBalls[0], recentHistory);
       
       return {
         recordId: record.id,
         record: record,
         analysis: analysis,
         timestamp: Date.now()
       };
     } catch (error) {
       console.error('诊断失败:', error);
       throw error;
     }
   };

   /**
    * 查看单个记录的诊断结果
    */
   const viewDiagnosis = async (record) => {
     try {
       setDiagnosisLoading(true);
       const result = await diagnoseSingleRecord(record);
       setDiagnosisResults([result]);
       setDiagnosisVisible(true);
       
       // 显示诊断结果提示
       if (result.analysis.totalDuplicates >= 2) {
         message.warning(`检测到风险：与前3期开奖号码重复${result.analysis.totalDuplicates}个数字！`);
       } else {
         message.success(`诊断完成：重复度较低，仅重复${result.analysis.totalDuplicates}个数字`);
       }
     } catch (error) {
       console.error('诊断失败:', error);
       message.error(`诊断失败: ${error.message}`);
     } finally {
       setDiagnosisLoading(false);
     }
   };

   /**
    * 一键诊断所有选号记录
    */
   const batchDiagnoseAllRecords = async () => {
     if (filteredRecords.length === 0) {
       message.warning('没有可诊断的选号记录');
       return;
     }

     try {
       setBatchDiagnosisLoading(true);
       const results = [];
       
       // 获取历史数据一次，避免重复查询
       const { DatabaseService } = await import('./database.js');
       const recentHistory = await DatabaseService.getRecentLotteryHistory(3);
       
       if (recentHistory.length === 0) {
         message.warning('暂无历史开奖记录，无法进行诊断。请先在历史记录页面同步数据。');
         return;
       }

       // 逐个诊断所有记录
       for (let i = 0; i < filteredRecords.length; i++) {
         const record = filteredRecords[i];
         try {
           const { redBalls, blueBalls } = formatNumbers(record.numbers);
           
           if (redBalls.length === 6 && blueBalls.length === 1) {
             const analysis = analyzeDuplication(redBalls, blueBalls[0], recentHistory);
             results.push({
               recordId: record.id,
               record: record,
               analysis: analysis,
               timestamp: Date.now()
             });
           }
         } catch (error) {
           console.error(`诊断记录 ${record.id} 失败:`, error);
         }
       }

       setDiagnosisResults(results);
       setDiagnosisVisible(true);
       
       // 统计诊断结果
       const highRiskCount = results.filter(r => r.analysis.riskLevel === 'high').length;
       const mediumRiskCount = results.filter(r => r.analysis.riskLevel === 'medium').length;
       const lowRiskCount = results.filter(r => r.analysis.riskLevel === 'low').length;
       
       message.success(
         `批量诊断完成！共诊断 ${results.length} 条记录，` +
         `高风险 ${highRiskCount} 条，中风险 ${mediumRiskCount} 条，低风险 ${lowRiskCount} 条`
       );
       
     } catch (error) {
       console.error('批量诊断失败:', error);
       message.error(`批量诊断失败: ${error.message}`);
     } finally {
       setBatchDiagnosisLoading(false);
     }
   };

   /**
    * 获取风险等级颜色
    */
   const getRiskLevelColor = (riskLevel) => {
     switch (riskLevel) {
       case 'high': return 'red';
       case 'medium': return 'orange';
       case 'low': return 'green';
       default: return 'default';
     }
   };

   /**
    * 获取风险等级图标
    */
   const getRiskLevelIcon = (riskLevel) => {
     switch (riskLevel) {
       case 'high': return <ExclamationCircleOutlined />;
       case 'medium': return <ExclamationCircleOutlined />;
       case 'low': return <CheckCircleOutlined />;
       default: return <MedicineBoxOutlined />;
     }
   };

   /**
    * 获取风险等级文本
    */
   const getRiskLevelText = (riskLevel) => {
     switch (riskLevel) {
       case 'high': return '高风险';
       case 'medium': return '中风险';
       case 'low': return '低风险';
       default: return '未知';
     }
   };

  /**
   * 获取算法图标
   */
  const getAlgorithmIcon = (algorithm) => {
    const iconMap = {
      'random': <ThunderboltOutlined />,
      'hot': <FireOutlined />,
      'cold': <CloudOutlined />,
      'smart': <BulbOutlined />,
      'calculator': <CalculatorOutlined />,
      'manual': <EyeOutlined />
    };
    return iconMap[algorithm] || <HistoryOutlined />;
  };

  /**
   * 获取算法标签颜色
   */
  const getAlgorithmColor = (algorithm) => {
    const colorMap = {
      'random': 'blue',
      'hot': 'red',
      'cold': 'cyan',
      'smart': 'gold',
      'calculator': 'green',
      'manual': 'purple'
    };
    return colorMap[algorithm] || 'default';
  };

  /**
   * 格式化数字显示
   */
  const formatNumbers = (numbers) => {
    if (!numbers || !numbers.red || !numbers.blue) {
      return { redBalls: [], blueBalls: [] };
    }
    
    return {
      redBalls: numbers.red.sort((a, b) => a - b),
      blueBalls: numbers.blue.sort((a, b) => a - b)
    };
  };

  // 初始化加载数据
  useEffect(() => {
    loadPickingRecords();
  }, [loadPickingRecords]);

  // 应用筛选条件
  useEffect(() => {
    applyFilters();
  }, [filters, pickingRecords, applyFilters]);

  // 表格列定义
  const columns = [
    {
      title: '选号时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: isMobile ? 100 : 150,
      sorter: (a, b) => a.id - b.id,
      render: (timestamp, record) => {
        // 优先使用createTime，其次使用timestamp，最后使用当前时间
        const timeToUse = record.createTime || record.timestamp || new Date().toISOString();
        const timeObj = dayjs(timeToUse);
        
        return (
          <div style={{ fontSize: isMobile ? '12px' : '14px' }}>
            <div>{timeObj.format('MM-DD HH:mm')}</div>
            {!isMobile && (
              <Text type="secondary" style={{ fontSize: '12px' }}>
                {timeObj.format('YYYY')}
              </Text>
            )}
          </div>
        );
      }
    },
    {
      title: '选号结果',
      key: 'numbers',
      render: (_, record) => {
        const { redBalls, blueBalls } = formatNumbers(record.numbers);
        return (
          <div style={{ fontSize: isMobile ? '12px' : '14px' }}>
            <Space size={2} wrap>
              {redBalls.map((num, index) => (
                <Tag key={`red-${index}`} color="red" style={{ 
                  margin: '1px',
                  fontSize: isMobile ? '10px' : '12px',
                  padding: isMobile ? '0 4px' : '0 6px'
                }}>
                  {String(num).padStart(2, '0')}
                </Tag>
              ))}
              {blueBalls.map((num, index) => (
                <Tag key={`blue-${index}`} color="blue" style={{ 
                  margin: '1px',
                  fontSize: isMobile ? '10px' : '12px',
                  padding: isMobile ? '0 4px' : '0 6px'
                }}>
                  {String(num).padStart(2, '0')}
                </Tag>
              ))}
            </Space>
          </div>
        );
      }
    },
    {
      title: '选号方式',
      key: 'algorithm',
      width: isMobile ? 80 : 120,
      filters: [
        { text: '随机选号', value: 'random' },
        { text: '热号选择', value: 'hot' },
        { text: '冷号选择', value: 'cold' },
        { text: '智能推荐', value: 'smart' },
        { text: '计算器', value: 'calculator' },
        { text: '手动选择', value: 'manual' }
      ],
      onFilter: (value, record) => record.algorithm === value,
      render: (_, record) => (
        <div>
          <Tag 
            icon={getAlgorithmIcon(record.algorithm)} 
            color={getAlgorithmColor(record.algorithm)}
            style={{ fontSize: isMobile ? '10px' : '12px' }}
          >
            {record.algorithm === 'random' ? '随机' :
             record.algorithm === 'hot' ? '热号' :
             record.algorithm === 'cold' ? '冷号' :
             record.algorithm === 'smart' ? '智能' :
             record.algorithm === 'calculator' ? '计算器' :
             record.algorithm === 'manual' ? '手动' : '未知'}
          </Tag>
          {!isMobile && (
            <div style={{ fontSize: '10px', color: '#999', marginTop: '2px' }}>
              {record.sourceName}
            </div>
          )}
        </div>
      )
    },
    {
       title: '操作',
       key: 'actions',
       width: isMobile ? 80 : 120,
       render: (_, record) => (
         <Space size="small">
           <Tooltip title="诊断分析">
             <Button
               type="text"
               size="small"
               icon={<MedicineBoxOutlined />}
               onClick={() => viewDiagnosis(record)}
               loading={diagnosisLoading}
             />
           </Tooltip>
           <Popconfirm
             title="确定删除这条记录吗？"
             onConfirm={() => deleteRecord(record.id)}
             okText="确定"
             cancelText="取消"
           >
             <Tooltip title="删除记录">
               <Button
                 type="text"
                 size="small"
                 danger
                 icon={<DeleteOutlined />}
               />
             </Tooltip>
           </Popconfirm>
         </Space>
       )
     }
  ];

  return (
    <div style={{ padding: isMobile ? '8px' : '16px' }}>
      {/* 页面标题和统计信息 */}
      <Card 
        className={isMobile ? 'mobile-card' : ''}
        style={{ marginBottom: isMobile ? 12 : 16 }}
      >
        <Row gutter={[16, 16]} align="middle">
          <Col flex="auto">
            <Title level={isMobile ? 4 : 3} style={{ margin: 0 }}>
              <HistoryOutlined style={{ marginRight: 8 }} />
              选号记录
            </Title>
          </Col>
          <Col>
            <Space>
              <Button
                type="primary"
                icon={<ReloadOutlined />}
                onClick={loadPickingRecords}
                loading={loading}
                size={isMobile ? 'small' : 'middle'}
              >
                {isMobile ? '' : '刷新'}
              </Button>
              {!isMobile && (
                <Popconfirm
                  title="确定清空所有选号记录吗？"
                  description="此操作不可恢复，请谨慎操作。"
                  onConfirm={clearAllRecords}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button
                    danger
                    icon={<ClearOutlined />}
                    size="middle"
                  >
                    清空记录
                  </Button>
                </Popconfirm>
              )}
            </Space>
          </Col>
        </Row>

        {/* 统计信息 */}
        <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
          <Col span={isMobile ? 8 : 6}>
            <Statistic
              title="总记录数"
              value={statistics.total}
              prefix={<DatabaseOutlined />}
              valueStyle={{ fontSize: isMobile ? '16px' : '20px' }}
            />
          </Col>
          <Col span={isMobile ? 8 : 6}>
            <Statistic
              title="今日选号"
              value={statistics.recentCount}
              prefix={<CalendarOutlined />}
              valueStyle={{ fontSize: isMobile ? '16px' : '20px' }}
            />
          </Col>
          <Col span={isMobile ? 8 : 12}>
            <div>
              <Text strong style={{ fontSize: isMobile ? '12px' : '14px' }}>算法分布</Text>
              <div style={{ marginTop: 4 }}>
                <Space size={4} wrap>
                  {Object.entries(statistics.algorithms).map(([algorithm, count]) => (
                    <Tag 
                      key={algorithm}
                      icon={getAlgorithmIcon(algorithm)}
                      color={getAlgorithmColor(algorithm)}
                      style={{ fontSize: isMobile ? '10px' : '12px' }}
                    >
                      {count}
                    </Tag>
                  ))}
                </Space>
              </div>
            </div>
          </Col>
        </Row>
      </Card>

      {/* 筛选工具栏 */}
      <Card 
        className={isMobile ? 'mobile-card' : ''}
        style={{ 
          marginBottom: isMobile ? 12 : 16,
          padding: isMobile ? '12px' : '16px'
        }}
      >
        <Row gutter={[8, 8]} align="middle">
          <Col xs={24} sm={6}>
            <Select
              placeholder="选择算法"
              value={filters.algorithm}
              onChange={(value) => setFilters(prev => ({ ...prev, algorithm: value }))}
              style={{ width: '100%' }}
              size={isMobile ? 'small' : 'middle'}
            >
              <Select.Option value="all">全部算法</Select.Option>
              <Select.Option value="random">随机选号</Select.Option>
              <Select.Option value="hot">热号选择</Select.Option>
              <Select.Option value="cold">冷号选择</Select.Option>
              <Select.Option value="smart">智能推荐</Select.Option>
              <Select.Option value="calculator">计算器</Select.Option>
              <Select.Option value="manual">手动选择</Select.Option>
            </Select>
          </Col>
          <Col xs={24} sm={8}>
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              value={filters.dateRange}
              onChange={(dates) => setFilters(prev => ({ ...prev, dateRange: dates }))}
              style={{ width: '100%' }}
              size={isMobile ? 'small' : 'middle'}
            />
          </Col>
          <Col xs={24} sm={6}>
            <Search
              placeholder="搜索号码或算法"
              value={filters.searchText}
              onChange={(e) => setFilters(prev => ({ ...prev, searchText: e.target.value }))}
              style={{ width: '100%' }}
              size={isMobile ? 'small' : 'middle'}
            />
          </Col>
          <Col xs={24} sm={4}>
            <Button
              icon={<FilterOutlined />}
              onClick={() => setFilters({ algorithm: 'all', dateRange: null, searchText: '', source: 'all' })}
              style={{ width: '100%' }}
              size={isMobile ? 'small' : 'middle'}
            >
              重置
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 主要内容 */}
      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        size={isMobile ? 'small' : 'default'}
        items={[
          {
            key: 'records',
            label: (
              <span>
                <TrophyOutlined />
                {!isMobile && ' 选号记录'}
              </span>
            ),
            children: (
              <Card 
                title={
                  <Space>
                    <TrophyOutlined />
                    <span>选号记录</span>
                    <Badge count={filteredRecords.length} showZero />
                  </Space>
                }
                className={isMobile ? 'mobile-card' : ''}
                 extra={
                   <Space>
                     <Button
                       type="primary"
                       icon={<MedicineBoxOutlined />}
                       onClick={batchDiagnoseAllRecords}
                       loading={batchDiagnosisLoading}
                       size={isMobile ? 'small' : 'middle'}
                     >
                       一键诊断
                     </Button>
                     <Button
                       icon={<ClearOutlined />}
                       onClick={cleanupAbnormalTimeData}
                       size={isMobile ? 'small' : 'middle'}
                       title="清理异常时间数据"
                     >
                       {!isMobile && '清理时间'}
                     </Button>
                     {!isMobile && (
                       <Tooltip title="导出数据">
                         <Button 
                           icon={<DownloadOutlined />} 
                           size="small"
                           onClick={() => message.info('导出功能开发中...')}
                         >
                           导出
                         </Button>
                       </Tooltip>
                     )}
                   </Space>
                 }
              >
                <Table
                  columns={columns}
                  dataSource={filteredRecords}
                  rowKey="id"
                  loading={loading}
                  size={isMobile ? 'small' : 'middle'}
                  scroll={isMobile ? { x: 600 } : undefined}
                  pagination={{
                    pageSize: isMobile ? 10 : 20,
                    showSizeChanger: !isMobile,
                    showQuickJumper: !isMobile,
                    showTotal: (total, range) => 
                      `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
                    ...(isMobile ? { simple: true } : {})
                  }}
                  locale={{
                    emptyText: (
                      <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description="暂无选号记录"
                      >
                        <Button type="primary" onClick={() => window.location.reload()}>
                          前往智能选号
                        </Button>
                      </Empty>
                    )
                  }}
                />
              </Card>
            )
          }
        ]}
      />

      {/* 诊断结果弹窗 */}
       <Modal
         title={
           <Space>
             <MedicineBoxOutlined />
             <span>诊断结果</span>
           </Space>
         }
         open={diagnosisVisible}
         onCancel={() => setDiagnosisVisible(false)}
         footer={null}
         width={isMobile ? '95%' : 1000}
         style={{ top: isMobile ? 20 : 50 }}
       >
         {diagnosisResults.length > 0 && (
           <div>
             {/* 诊断结果统计 */}
             <Alert
               message={`诊断完成，共检测 ${diagnosisResults.length} 条记录`}
               description={
                 <div>
                   <Text>
                     高风险: {diagnosisResults.filter(r => r.analysis.riskLevel === 'high').length} 条，
                     中风险: {diagnosisResults.filter(r => r.analysis.riskLevel === 'medium').length} 条，
                     低风险: {diagnosisResults.filter(r => r.analysis.riskLevel === 'low').length} 条
                   </Text>
                 </div>
               }
               type="info"
               showIcon
               style={{ marginBottom: 16 }}
             />

             {/* 诊断结果列表 */}
             <List
               dataSource={diagnosisResults}
               renderItem={(result, index) => {
                 const { redBalls, blueBalls } = formatNumbers(result.record.numbers);
                 const analysis = result.analysis;
                 
                 return (
                   <List.Item>
                     <Card
                       size="small"
                       style={{ width: '100%' }}
                       title={
                         <Space>
                           <Text strong>#{index + 1}</Text>
                           <Tag 
                             icon={getRiskLevelIcon(analysis.riskLevel)}
                             color={getRiskLevelColor(analysis.riskLevel)}
                           >
                             {getRiskLevelText(analysis.riskLevel)}
                           </Tag>
                         </Space>
                       }
                     >
                       {/* 选号显示 */}
                       <div style={{ marginBottom: 12 }}>
                         <Text strong>选号: </Text>
                         <Space size={2} wrap>
                           {redBalls.map((num, idx) => (
                             <Tag key={`red-${idx}`} color="red" style={{ fontSize: '12px' }}>
                               {String(num).padStart(2, '0')}
                             </Tag>
                           ))}
                           {blueBalls.map((num, idx) => (
                             <Tag key={`blue-${idx}`} color="blue" style={{ fontSize: '12px' }}>
                               {String(num).padStart(2, '0')}
                             </Tag>
                           ))}
                         </Space>
                       </div>

                       {/* 诊断结果 */}
                       <Row gutter={[16, 8]}>
                         <Col span={8}>
                           <Statistic
                             title="总重复数"
                             value={analysis.totalDuplicates}
                             valueStyle={{ fontSize: '16px' }}
                           />
                         </Col>
                         <Col span={8}>
                           <Statistic
                             title="红球重复"
                             value={analysis.redDuplicates}
                             valueStyle={{ fontSize: '16px', color: '#ff4d4f' }}
                           />
                         </Col>
                         <Col span={8}>
                           <Statistic
                             title="蓝球重复"
                             value={analysis.blueDuplicates}
                             valueStyle={{ fontSize: '16px', color: '#1890ff' }}
                           />
                         </Col>
                       </Row>

                       {/* 风险进度条 */}
                       <div style={{ marginTop: 12 }}>
                         <Text strong>风险等级: </Text>
                         <Progress
                           percent={
                             analysis.riskLevel === 'high' ? 100 :
                             analysis.riskLevel === 'medium' ? 60 :
                             analysis.riskLevel === 'low' ? 20 : 0
                           }
                           status={
                             analysis.riskLevel === 'high' ? 'exception' :
                             analysis.riskLevel === 'medium' ? 'active' : 'success'
                           }
                           size="small"
                           showInfo={false}
                         />
                       </div>

                       {/* 建议 */}
                       {analysis.suggestions.length > 0 && (
                         <div style={{ marginTop: 12 }}>
                           <Text strong>建议: </Text>
                           <Text type="secondary">{analysis.suggestions[0]}</Text>
                         </div>
                       )}

                       {/* 重复详情 */}
                       {analysis.duplicateDetails.length > 0 && (
                         <div style={{ marginTop: 12 }}>
                           <Text strong>重复详情: </Text>
                           <div style={{ marginTop: 4 }}>
                             {analysis.duplicateDetails.slice(0, 3).map((detail, idx) => (
                               <div key={idx} style={{ fontSize: '12px', color: '#666' }}>
                                 {detail.period}: 
                                 {detail.redMatches.length > 0 && (
                                   <span>
                                     红球重复 {detail.redMatches.length} 个：
                                     【{detail.redMatches.map(num => String(num).padStart(2, '0')).join('，')}】
                                   </span>
                                 )}
                                 {detail.blueMatch && (
                                   <span>
                                     {detail.redMatches.length > 0 && '，'}
                                     蓝球重复：【{String(detail.blueNumber).padStart(2, '0')}】
                                   </span>
                                 )}
                               </div>
                             ))}
                             {analysis.duplicateDetails.length > 3 && (
                               <Text type="secondary" style={{ fontSize: '12px' }}>
                                 ...还有 {analysis.duplicateDetails.length - 3} 期重复
                               </Text>
                             )}
                           </div>
                         </div>
                       )}
                     </Card>
                   </List.Item>
                 );
               }}
               pagination={{
                 pageSize: 5,
                 size: 'small',
                 showSizeChanger: false
               }}
             />
           </div>
         )}
       </Modal>

      {/* 移动端额外操作 */}
      {isMobile && (
        <Card style={{ marginTop: 12 }}>
          <Space style={{ width: '100%', justifyContent: 'center' }} wrap>
            <Popconfirm
              title="确定清空所有选号记录吗？"
              onConfirm={clearAllRecords}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                danger
                icon={<ClearOutlined />} 
                size="small"
              >
                清空记录
              </Button>
            </Popconfirm>
            <Button 
              icon={<DownloadOutlined />} 
              onClick={() => message.info('导出功能开发中...')}
              size="small"
            >
              导出数据
            </Button>
          </Space>
        </Card>
      )}
    </div>
  );
};

export default LotteryPickingRecords;